//
//  LiftIMChatManager.m
//  AAIM
//
//  Created by awhMAC on 2019/12/21.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "LiftIMChatManager.h"
#import "BTMessageModel.h"
#import "ImageMessageModel.h"
#import "VoiceMessageModel.h"
#import "TextMessageModel.h"
@interface LiftIMChatManager ()


@end
@implementation LiftIMChatManager

#pragma mark - public methods
- (void)addDelegate:(id<LiftIMChatMangerDelegate>)delegate {
    BOOL isExsit = NO;
    for (NSValue *delegateValue in self.delegates) {
        id<LiftIMChatMangerDelegate> d = delegateValue.nonretainedObjectValue;
        if (delegate == d) {
            isExsit = YES;
            break;
        }
    }
    if (!isExsit) {
        NSValue *delegateValue = [NSValue valueWithNonretainedObject:delegate];
        [self.delegates addObject:delegateValue];
    }
}

- (void)removeDelegate:(id<LiftIMChatMangerDelegate>)delegate {
    for (NSValue *delegateValue in self.delegates) {
        id<LiftIMChatMangerDelegate> d = delegateValue.nonretainedObjectValue;
        if (delegate == d) {
             [self.delegates removeObject:delegateValue];
            break;
        }
    }
}
#pragma mark - 发送消息
- (void)sendMessage:(BTMessageModel *)message complete:(void(^)(NSDictionary *info, NSError *error))complete {
    if (message.msgtype==MessageTypeText) {
        [self sendTextMessage:message complete:complete];
    }else if (message.msgtype==MessageTypeImage)
    {
        [self sendImageMessage:message complete:complete];
        
    }else if (message.msgtype==MessageTypeVoice)
    {
        [self sendVoiceMessage:message complete:complete];
    }
}
- (void)sendTextMessage:(BTMessageModel *)message complete:(void(^)(NSDictionary *info, NSError *error))complete {
    TextMessageModel * textModel =(TextMessageModel *)message;
    NSDictionary * messageInfo;
    if (textModel.chatType == ChatTypeFriend) {
        messageInfo =@{@"data":@{@"msg":textModel.content,@"f_uuid":textModel.fuuid,@"head":textModel.head,@"rfuuid":textModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",textModel.msgtype]},@"sign":@"1111"};
    }else if (textModel.chatType==ChatTypeGroup)
    {
        messageInfo =@{@"data":@{@"msg":textModel.content,@"f_uuid":textModel.fuuid,@"head":textModel.head,@"g_id":textModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",textModel.msgtype]},@"sign":@"1111"};
    }
    [[LiftIMClient sharedClient] sendMessage:messageInfo.JSONString messageType:textModel.chatType complete:complete];
}
// 发送图片消息
- (void)sendImageMessage:(BTMessageModel *)message complete:(void(^)(NSDictionary *info, NSError *error))complete {
    ImageMessageModel *imageModel = (ImageMessageModel *)message;
    [[NetWorkTool shareInstance] uploadChattingImage:imageModel.image completion:^(SLResultModel * _Nonnull res) {
        AAIMLog(@"上传图片结果====%@",res.rawdata);
        if (res.rawdata) {
            NSString *urlStr = res.rawdata[@"data"];
            imageModel.src = urlStr;
        } else {
            NSError *error = [NSError errorWithDomain:@"图片上传失败" code:-1 userInfo:nil];
            complete ? complete(nil, error) : nil;
            return;
        }
        NSDictionary * messageInfo;
        if (imageModel.chatType == ChatTypeFriend) {
            messageInfo =@{@"data":@{@"msg":imageModel.src,@"f_uuid":imageModel.fuuid,@"head":imageModel.head,@"rfuuid":imageModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",imageModel.msgtype]},@"sign":@"1111"};
        }else if (imageModel.chatType==ChatTypeGroup)
        {
            messageInfo =@{@"data":@{@"msg":imageModel.src,@"f_uuid":imageModel.fuuid,@"head":imageModel.head,@"g_id":imageModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",imageModel.msgtype]},@"sign":@"1111"};
        }
        [[LiftIMClient sharedClient] sendMessage:messageInfo.JSONString messageType:imageModel.chatType complete:complete];
    }];
}
- (void)sendVoiceMessage:(BTMessageModel *)message complete:(void(^)(NSDictionary *info, NSError *error))complete {
    VoiceMessageModel *voiceModel = (VoiceMessageModel *)message;
    [[NetWorkTool shareInstance] uploadVoiceFile:voiceModel.path completion:^(SLResultModel * _Nonnull res) {
        if (res.rawdata) {
            voiceModel.src = res.rawdata[@"data"];
        } else {
            NSError *error = [NSError errorWithDomain:@"语音上传失败" code:-1 userInfo:nil];
            complete ? complete(nil,error) : nil;
            return;
        }
        if ([NSObject ldy_isEmpty:voiceModel.src]) {
            NSError *error = [NSError errorWithDomain:@"语音上传失败" code:-1 userInfo:nil];
            complete ? complete(nil,error) : nil;
            return;
        }
        NSDictionary * messageInfo;
        if (voiceModel.chatType == ChatTypeFriend) {
            messageInfo =@{@"data":@{@"msg":voiceModel.src,@"f_uuid":voiceModel.fuuid,@"head":voiceModel.head,@"rfuuid":voiceModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",voiceModel.msgtype],@"remark":[NSString stringWithFormat:@"%ld",voiceModel.duration]},@"sign":@"1111"};
        }else if (voiceModel.chatType==ChatTypeGroup)
        {
            messageInfo =@{@"data":@{@"msg":voiceModel.src,@"f_uuid":voiceModel.fuuid,@"head":voiceModel.head,@"g_id":voiceModel.rfuuid,@"clientuuid":[LoginManager shareLoginManager].userModel.uuid,@"msgtype":[NSString stringWithFormat:@"%ld",voiceModel.msgtype],@"remark":[NSString stringWithFormat:@"%ld",voiceModel.duration]},@"sign":@"1111"};
        }
        [[LiftIMClient sharedClient] sendMessage:messageInfo.JSONString messageType:voiceModel.chatType complete:complete];
        NSLog(@"上传结果：%@",res.rawdata);
    }];
}
#pragma mark - 接收消息处理
- (void)receivedMessages:(NSArray<BTMessageModel *> *)messages {
    NSMutableArray<BTMessageModel *> *notyMessages = [NSMutableArray new];
    if (messages == nil || messages.count <= 0) return;
    BTMessageModel *obj = messages[0];
    obj.messageDirection = MessageDirectionReceive;
    obj.unreadCount = obj.msgtype == MessageTypeRecall ? 0 : 1;
    [notyMessages removeAllObjects];
    BTMessageModel *messageSubModel = [BTMessageModel new];
    if (obj.msgtype == MessageTypeText || obj.msgtype == MessageTypeAPPURL ||obj.msgtype==MessageTypeBrowserURL || obj.msgtype==MessageTypeSystem) {
        messageSubModel = [TextMessageModel mj_objectWithKeyValues:obj.mj_keyValues];
        [notyMessages addObject:messageSubModel];
        [self postNotifications:messages];
    } else if (obj.msgtype == MessageTypeImage) {
        ImageMessageModel *imageMessage = [ImageMessageModel mj_objectWithKeyValues:obj.mj_keyValues];
        imageMessage.width = SCREEN_WIDTH * 0.25;
        imageMessage.height = imageMessage.width * 1.5;
        // 赋值图片文件存储地址
        long long time = [ChatTool shareChatTool].currentTimestamp;
        NSString *fileName = [NSString stringWithFormat:@"%lld.png",time];
        NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        doucument = [doucument stringByAppendingPathComponent:kMessageImageFileName];
        NSString *fullpath = [doucument stringByAppendingPathComponent:fileName];
        imageMessage.path = fullpath;
        messageSubModel = imageMessage;
        [notyMessages addObject:messageSubModel];
        //            [self downLoadImageFile:imageMessage];
        [self postNotifications:@[imageMessage]];
    }else if (obj.msgtype == MessageTypeVoice)
    {
        VoiceMessageModel *voiceMessage = (VoiceMessageModel *)[VoiceMessageModel mj_objectWithKeyValues:obj.mj_keyValues];
        // 赋值录音文件时长
        voiceMessage.duration =[voiceMessage.remark integerValue];
        // 赋值录音文件存储地址
        long long time = [ChatTool shareChatTool].currentTimestamp;
        voiceMessage.timestamp=time;
        NSString *fileName = [NSString stringWithFormat:@"%lld.wav",time];
        NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        doucument = [doucument stringByAppendingPathComponent:kMessageVoiceFileName];
        NSString *fullpath = [doucument stringByAppendingPathComponent:fileName];
        voiceMessage.path = fullpath;
        messageSubModel = voiceMessage;
        [notyMessages addObject:messageSubModel];
        [self downloadVoiceFile:(VoiceMessageModel *)messageSubModel];
    }
}

#pragma mark - 私有方法

// 通知代理
- (void)postNotifications:(NSArray<BTMessageModel *> *)messages {
    //    dispatch_async(dispatch_get_main_queue(), ^{
    [self.delegates enumerateObjectsUsingBlock:^(NSValue *delegateValue, NSUInteger idx, BOOL * _Nonnull stop) {
        id<LiftIMChatMangerDelegate> delegate = delegateValue.nonretainedObjectValue;
        if ([delegate respondsToSelector:@selector(messagesDidReceive:)]) {
            [delegate messagesDidReceive:messages];
        }
    }];
    //    });
}
- (void)downloadVoiceFile:(VoiceMessageModel *)voiceMessage {
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NetWorkTool shareInstance] downloadVoiceFile:voiceMessage.msg targetPath:voiceMessage.path progress:nil completion:^(NSError * _Nonnull error) {
            if (!error) {
                // 语音文件下载成功
                [self postNotifications:@[voiceMessage]];
            }
        }];
//    });
}
#pragma mark - getter
- (NSMutableArray *)delegates {
    if (!_delegates) {
        _delegates = [NSMutableArray new];
    }
    return _delegates;
}


@end
